package com.pd.dong.generate.plugins;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;

/**
 * @author dongpeng32
 * @time 2020/9/22
 */
public class ModelExtPlugin extends BasePlugin {

    @Override
    public boolean modelFieldGenerated(Field field,
                                       TopLevelClass topLevelClass,
                                       IntrospectedColumn introspectedColumn,
                                       IntrospectedTable introspectedTable,
                                       ModelClassType modelClassType) {

        field.addJavaDocLine("/** " + introspectedColumn.getRemarks() + " */");
        return true;
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        // 拷贝对象方法
        Method methodCopy = new Method("copy");
        methodCopy.setVisibility(JavaVisibility.PUBLIC);
        methodCopy.addJavaDocLine("/** ");
        methodCopy.addJavaDocLine(" * 拷贝，将对象中的字段全部拷贝到子对象中");
        methodCopy.addJavaDocLine(" * @param bean 接收对象的子类");
        methodCopy.addJavaDocLine(" * @return 拷贝完成后的子类");
        methodCopy.addJavaDocLine(" */ ");
        methodCopy.setName("<T extends " + topLevelClass.getType().getShortName() + "> T copy");
        methodCopy.setReturnType(new FullyQualifiedJavaType(""));
        methodCopy.addParameter(new Parameter(new FullyQualifiedJavaType("T"), "bean"));

        for (IntrospectedColumn column : introspectedTable.getAllColumns()) {
            String columnName = column.getJavaProperty();
            String methodName = Character.toUpperCase(columnName.charAt(0)) + columnName.substring(1);
            methodCopy.addBodyLine("bean.set" + methodName + "(get" + methodName + "());");
        }
        methodCopy.addBodyLine("return bean;");

        topLevelClass.addMethod(methodCopy);
        return true;
    }
}
